package com.jsb.laundry.common.design_service.pay.properties;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Properties;


/**
 * 读取 微信小程序 支付配置文件
 *
 * @author zmy
 * @create 2022-12-10 12:01
 */
//@RefreshScope // 开启自动刷新
@Component
@Data
@NoArgsConstructor
@AllArgsConstructor
@ConfigurationProperties(prefix = "user.wechat.app")
public class WechatAPPPayProperties {
    private static final Logger LOGGER = LoggerFactory.getLogger(WechatAPPPayProperties.class);

    {
        Properties properties = System.getProperties();
        OS = properties.get("os.name").toString();
        privateKeyPath = CopyJarInnerResourceUtil.getJarInnerResource("apiclient_key.pem");
        wechatPayCertificatePath = CopyJarInnerResourceUtil.getJarInnerResource("wechatpay_7532B3E24A309263A2047852891DFC660FDC2746.pem");

        LOGGER.info("privateKeyPath: " + privateKeyPath);
        LOGGER.info("wechatPayCertificatePath: " + wechatPayCertificatePath);
    }

    /**
     * 操作系统名
     */
    public static String OS;
    /**
     * APPID
     */
    private String appId;
    /**
     * 商户号
     */
    private String merchantId;

    private String appSecret;
    /**
     * 商户证书序列号
     */
    private String merchantSerialNumber;
    /**
     * 微信支付 APIv3 密钥
     */
    private String apiV3Key;
    /**
     * 商户API私钥路径
     */
    public static String privateKeyPath;
    /**
     * 微信支付平台证书路径
     */
    public static String wechatPayCertificatePath;

    //=================================回调地址=====================================================
    /**
     * 回调地址标识字段
     */
    public static String callbackUrl = "CallbackUrl";
    /**
     * 便民洗衣支付成功回调(购物车、普通活动回调)
     */
    private String laundryCallbackUrlCartOrActivity;
    /**
     * 月卡 298 398 回调
     */
    private String laundryCallbackUrlMonthCard;
    /**
     * vip 回调
     */
    private String laundryCallbackUrlVip;
    /**
     * 校服 回调
     */
    private String laundryCallbackUrlSchool;

    //==========================================================================================

    /**
     * 退款成功回调地址
     */
    private String refundCallbackUrl;


    private static class CopyJarInnerResourceUtil {

        /**
         * 复制证书时标识
         **/
        private static final String SPECIAL_FLAG = "JSB-20221107";

        /**
         * 复制证书
         * 源文件：wxpay/fileName
         * 生成目标：与jar包同级的 jsbConfig/wxpay/fileName
         *
         * @param fileName 要读取的文件名
         * @return
         */
        public static String getJarInnerResource(String fileName) {
            // 源文件目录
            String srcDir = "wxpay";
            // 要生成的目录
            String destDir = "jsbConfig/" + srcDir;
            //读取jar包内文件
            InputStream is = CopyJarInnerResourceUtil.class.getResourceAsStream("/" + srcDir + "/" + fileName);

            //若文件已存在，则返回的filePath中含有"JSB"，则不需再重写文件
            String filePath = createFile(destDir, fileName);

            //文件不存在时，则将流写入文件
            if (filePath.indexOf(SPECIAL_FLAG) == 0) {
                String path = filePath.substring(SPECIAL_FLAG.length());
                File file = new File(path);
                outputStream(is, file);
                return path;
            }
            return filePath;
        }

        /**
         * 创建目录、文件
         *
         * @param createDir
         * @param filename
         * @return
         */
        private static String createFile(String createDir, String filename) {
            String path = System.getProperty("user.dir");
            //create 文件夹
            String dirPath = path + "/" + createDir;
            File dir = new File(dirPath);
            dir.mkdirs();
            //create 文件
            String filePath = dirPath + "/" + filename;
            File file = new File(filePath);
            // 文件不存在时，则创建文件。返回的路径中有JSB20221107
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return SPECIAL_FLAG + filePath;
            }
            // 文件存在直接返回路径
            return filePath;
        }

        /**
         * 流写入到文件
         *
         * @param is
         * @param file
         */
        private static void outputStream(InputStream is, File file) {
            OutputStream os = null;
            try {
                os = new FileOutputStream(file);
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.close();
                is.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


